<?php
/* --------------------------------------------------------------
   shipping_status.php 2011-04-15 gambio
   Gambio GmbH
   http://www.gambio.de
   Copyright (c) 2011 Gambio GmbH
   Released under the GNU General Public License (Version 2)
   [http://www.gnu.org/licenses/gpl-2.0.html]
   --------------------------------------------------------------
*/

/*
 * set the shipping status based on the number of items
 * 
 * @param int $p_product_id Product id
 * @return bool ture:OK
 */
function set_shipping_status($p_product_id)
{
	// check if the configuration is set to change the shipping status
	$auto_shipping_status = gm_get_conf('GM_AUTO_SHIPPING_STATUS');
	if($auto_shipping_status == 'false' || ACTIVATE_SHIPPING_STATUS == 'false' || STOCK_LIMITED == 'false') {
		return true;
	}
	// determine delivery time of the article
	$t_query = '
		SELECT 
			products_shippingtime,
			products_quantity
		FROM '.TABLE_PRODUCTS.'
			WHERE products_id = \''.xtc_get_prid($p_product_id).'\'
	';
	$t_shippingtime_query = xtc_db_query($t_query);
	$t_shippingtime_values = xtc_db_fetch_array($t_shippingtime_query);
	$t_shippingtime_id = $t_shippingtime_values['products_shippingtime'];
	$t_products_quantity = $t_shippingtime_values['products_quantity'];

	// determine actual delivery time of the article
	$t_query = '
		SELECT shipping_quantity
		FROM '.TABLE_SHIPPING_STATUS.'
			WHERE shipping_status_id = \''.xtc_get_prid($shippingtime_id).'\'
	';
	$t_shipping_quantity_query = xtc_db_query($t_query);
	$t_shipping_quantity_values = xtc_db_fetch_array($t_shipping_quantity_query);
	$t_shipping_quantity = $t_shipping_quantity_values['shipping_quantity'];

	// check if the delivery time must change
	if($t_shipping_quantity <= $t_products_quantity) {
		$t_query = '
			SELECT
				shipping_status_id
			FROM '.TABLE_SHIPPING_STATUS.'
				WHERE shipping_quantity >= \''.$t_products_quantity.'\'
			ORDER BY shipping_quantity ASC
			LIMIT 1';
		$t_new_shipping_status_query = xtc_db_query($t_query);
		$t_new_shipping_status_values = xtc_db_fetch_array($t_new_shipping_status_query);
		$t_shipping_status_id_new = $t_new_shipping_status_values['shipping_status_id'];

		if($t_shipping_status_id_new > 0) {
			$t_query = '
				UPDATE '.TABLE_PRODUCTS.'
				SET products_shippingtime = \''.($t_shipping_status_id_new).'\'
					WHERE products_id = \''.xtc_get_prid($p_product_id).'\'
			';
			xtc_db_query($t_query);
		}
	}
	return true;
}
?>